package com.inspur.icity.bus.api.user.task;

import com.inspur.icity.bus.api.user.model.BusBaseData;
import com.inspur.icity.bus.api.user.model.BusRoute;
import com.inspur.icity.bus.api.user.model.BusSite;
import com.inspur.icity.bus.api.user.service.BusBaseDataService;
import com.inspur.icity.bus.api.user.service.BusRouteService;
import com.inspur.icity.bus.api.user.service.BusSiteService;
import com.inspur.icity.bus.base.core.inspurresult.BusRouter;
import com.inspur.icity.bus.base.core.inspurresult.BusRouterResult;
import com.inspur.icity.bus.base.core.inspurresult.BusStationResult;
import com.inspur.icity.bus.base.core.util.InspurApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 定时任务类
 * Created By SOA
 * Date: 2018/1/10
 * Time: 13:51
 */
@Component
public class TaskSaveRouteSite {

    private  static Logger logger = LoggerFactory.getLogger(TaskSaveRouteSite.class);

    private Set<String> codes = new HashSet<>();

    @Autowired
    private BusRouteService busRouteService;

    @Autowired
    private BusSiteService busSiteService;

    @Autowired
    private BusBaseDataService baseDataService;

    /**
     * 保存线路站点
     */
    @Scheduled(cron = "0 39 1 * * ?")
    public void saveRouteSiteTask(){
        long now = System.currentTimeMillis();
        logger.info("定时任务开启--获取线路站点");
        Map<String,Object> map = new HashMap<>();
        map.put("flag",2); // 1：公交查询，2：好运巴士（济南）
        List<BusBaseData> list = baseDataService.find(map);
        saveRouteSite(list); //获取线路、站点
        logger.info("定时任务结束--耗时："+(System.currentTimeMillis() - now));
    }


    /**
     * 业务处理，。
     */
    @Transactional("apiTM")
    public void saveRouteSite(List<BusBaseData> list){
        /*
        遍历城市
         */
        for(BusBaseData busBaseData : list){
            List<BusRoute> busRoutes = getBusRoute(busBaseData);
            if(null == busRoutes || busRoutes.size() <= 0){
                return;
            }
            //获取所有站点信息
            List<BusSite> busStations = getBusSite(busRoutes,busBaseData);

            //批量删除线路
            busRouteService.batchDelete(busRoutes);
            //批量插入线路
            busRouteService.batchSave(busRoutes);

            //批量删除站点
            busSiteService.batchDelete(busStations);
            //批量插入站点信息
            busSiteService.batchSave(busStations);
        }
    }

    /**
     * 获取线路信息（目前四个地区）
     * @return
     */
    public List<BusRoute> getBusRoute(BusBaseData busBaseData){
        List<BusRoute> result = new ArrayList<>();
        BusRouterResult busRouterResult = InspurApi.queryAllRoutes(busBaseData.getIcityUri(),busBaseData.getCode(),""); //routeName为空字符时，获取所有线路
        if (busRouterResult != null && busRouterResult.getStatus() != null && "0000".equals(busRouterResult.getStatus())){
            List<BusRouter> busRouters = busRouterResult.getBusRouters();
            if(null != busRouters){
                for(BusRouter busRouter : busRouters){
                    BusRoute busRoute = new BusRoute();
                    busRoute.setAreacode(busBaseData.getCode());
                    busRoute.setRouteId(Integer.parseInt(busRouter.getRouteid()));
                    busRoute.setRouteName(busRouter.getRouteName());
                    busRoute.setUpdown(Integer.parseInt(busRouter.getUpdown()));
                    busRoute.setDirection(busRouter.getEndStationName()+"方向"); //方向
                    busRoute.setBeginStationName(busRouter.getBeginStationName());
                    busRoute.setEndStationName(busRouter.getEndStationName());
                    busRoute.setFirstOrder(busRouter.getFirstOrder());
                    busRoute.setLastOrder(busRouter.getLastOrder());
                    busRoute.setStationCount(Integer.parseInt(busRouter.getStationCount()));
                    busRoute.setTicket(busRouter.getTicket()); //票价
                    busRoute.setCreateTime(new Date());
                    result.add(busRoute);
                }
                //记录新获取数据的系统代码
                codes.add(busBaseData.getCode());
            }
        }
        return result;
    }

    /**
     * 获取站点信息
     */
    public List<BusSite> getBusSite(List<BusRoute> busRoutes,BusBaseData busBaseData){
        List<BusSite> result = new ArrayList<>();
        Map<String,Object> map = null;
        for(BusRoute busRoute : busRoutes){
            BusStationResult busStationResult = InspurApi.getStations(busBaseData.getIcityUri(),busRoute.getAreacode(), String.valueOf(busRoute.getRouteId()), String.valueOf(busRoute.getUpdown()));
            if(busStationResult != null && busStationResult.getStatus() != null && "0000".equals(busStationResult.getStatus())){
                List<com.inspur.icity.bus.base.core.inspurresult.BusStation> busStations = busStationResult.getBusStations();
                for(com.inspur.icity.bus.base.core.inspurresult.BusStation busStation : busStations){
                    BusSite site = new BusSite();
                    site.setStationName(busStation.getStationName());
                    site.setStationIndex(Integer.parseInt(busStation.getStationIndex()));
                    site.setLng(Double.parseDouble(busStation.getLongitude()));
                    site.setLat(Double.parseDouble(busStation.getLatitude()));
                    site.setRouteName(busRoute.getRouteName());
                    site.setRouteId(busRoute.getRouteId());
                    site.setAreacode(busRoute.getAreacode());
                    site.setDirection(busRoute.getEndStationName()+"方向");
                    site.setUpdown(busRoute.getUpdown());
                    site.setCreatetime(new Date());
                    result.add(site);
                }
                //记录新获取数据的系统代码
                codes.add(busRoute.getAreacode());
            }
        }
        return result;
    }
}
